from common.logger_util import LogUtils
import jmespath
from common.exceptions import (
    ParamsError
    )


class ResponseObject():
    def __init__(self, request_resp):
        
        try:
            body = request_resp.json()
        except:
            body = request_resp.content

        self.body = body
        self.status_code = request_resp.status_code
    def __getattr__(self, key):
        if key in ["json", "content", "body"]:
            try:
                value = self.resp_obj.json()
            except ValueError:
                value = self.resp_obj.content
        elif key == "cookies":
            value = self.resp_obj.cookies.get_dict()
        else:
            try:
                value = getattr(self.resp_obj, key)
            except AttributeError:
                err_msg = "ResponseObject does not have attribute: {}".format(key)
                LogUtils.error(err_msg)
                raise ParamsError(err_msg)

        self.__dict__[key] = value
        return value
    
    def load_extract(self,extracts, shared_data):
        for k in extracts:

            value = self._search_jmespath(extracts[k])
            shared_data[k] = value

    def _search_jmespath(self, expr:str):
        resp_obj_meta = {
            "status_code": self.status_code,
            "body": self.body,
        }
        if not expr.startswith(tuple(resp_obj_meta.keys())):
            if hasattr(self.resp_obj,expr):
                return getattr(self.resp_obj,expr)
            else:
                return expr

        try:
            check_value = jmespath.search(expr, resp_obj_meta)
        except Exception as ex:
            LogUtils.error(
                f"failed to search with jmespath\n"
                f"expression: {expr}\n"
                f"data: {resp_obj_meta}\n"
                f"exception: {ex}"
            )
            raise

        return check_value